import siteInfo 	  from './siteinfo.js'
import HttpService  from 'helpers/HttpService'
import WxService    from 'assets/plugins/wx-service/WxService'


//app.js

var modules = [{
    name: "siteInfo",
    file: "./siteinfo.js"
}, {
	name: 'WxParse',
	file: "./helpers/wxParse/wxParse.js"
}, {
    name: "page",
    file: "./core/page.js"
}, {
  name: "core",
  file: "./core/core.js"
}, {
  name: "util",
  file: "./core/util.js"
}]

var args = {
  onLaunch: function (options) {
    var that              = this
    wx.getSystemInfo({
      success: function (res) {
        that.screenWidth  = res.windowWidth;
        that.screenHeight = res.windowHeight;
        that.pixelRatio   = res.pixelRatio;
      }
    });
  },
  HttpService: new HttpService({
      baseURL: siteInfo.siteroot
  }, {
      version:          siteInfo.version,
  }),
  WxService: new WxService(),
  login() {
    return this.wechatSignIn()
  },
  wechatSignIn() {
      let that = this
      if (this.WxService.getStorageSync('session')) {
          return this.WxService.checkSession().then(function() {
              return new Promise((resolve, reject) => {
                  resolve(wx.getStorageSync('userInfo'))
              })
          }, function() {
              console.log('login fail')
              that.WxService.removeStorageSync('session')
              return that.wechatSignIn()
          })
          return new Promise((resolve, reject) => {
              resolve(wx.getStorageSync('userInfo'))
          })
      }
      wx.showToast({
          title: '登录中',
          icon: 'loading'
      })
      return this.WxService.login()
          .then(data => {
              return this.HttpService.wechatSignIn({
                  code: data.code
              })
          })
          .then(data => {
              console.log(data)
              if (data.meta.code == 0) {
                  this.WxService.setStorageSync('openid', data.data.openid)
                  this.WxService.setStorageSync('session', data.data.session)
                  if (data.data.init === true)
                      wx.navigateTo({
                          url: '/pages/login/index'
                      })
                  // return this.wechatDecryptData().then(data => {
                  //     this.globalData.userInfo = data.data.userInfo
                  //     wx.setStorageSync('userInfo', data.data.userInfo)
                  //     wx.setStorageSync('session', data.data.session)
                  //     return new Promise((resolve, reject) => {
                  //         resolve(data)
                  //     })
                  // })
                  else {
                      this.globalData.userInfo = data.data.userInfo
                      wx.setStorageSync('userInfo', data.data.userInfo)
                      let openid
                      if (openid = wx.getStorageSync('invite_openid')) {
                          console.log(openid, 'openid')
                          wx.removeStorageSync('invite_openid')
                          this.HttpService.bindRetailRelationShip({ openid: openid })
                      }
                  }
  
                  return new Promise((resolve, reject) => {
                      resolve(data)
                  })
  
              } else if (data.meta.code == 40029) {
                  // 登陆失败，重新授权
                  this.showModal()
              }
          })
  },   	
  navigateTo(param) {
      let url = param.url
      if (param.param) {
          param.url += '?' + this.toParamStr(param.param)
      }
      console.log(param.url, 'url')
      wx.navigateTo({
          url: param.url,
          fail() {
              wx.switchTab({
                  url,
                  fail() {
                      wx.reLaunch({ url: param.url })
                  }
              })
          }
      })
  },
  setFormId(e) {
      let formId = e.detail ? e.detail.formId : ''
      if (formId && formId != 'the formId is a mock one') {
          // this.HttpService.addFormId({ form_id: formId })
      }
  },
  openEvent(e, t) {
      let o = this
      o.setFormId(e)
      let event = e.currentTarget.dataset == {} ? e.target.dataset : e.currentTarget.dataset
      console.log(event, 'ev')
      switch (event.type) {
          case '1':
              if (event.url) {
                  let to = { url: event.url }
                  o.navigateTo(to)
              }
              break
          case 'switchTab':
              wx.switchTab({
                url: event.url,
                fail() {
                  wx.reLaunch({ url: event.url })
                }
              })
              break;
          case 'redirect':
              wx.redirectTo({
                url: event.url,
                fail() {
                  wx.reLaunch({ url: event.url })
                }
              })
              break;
          case '2':
              // o.makePhoneCall(event.phonenumber)
              wx.makePhoneCall({
                  phoneNumber: event.phonenumber ? event.phonenumber : event.tel //仅为示例，并非真实的电话号码
              })
              break
          case '3':
              wx.navigateToMiniProgram({ appId: event.appid })
              break
          case '4':
              let srcs
              try{
                 srcs = event.srcs.split(',')
              } catch (e) {
                 srcs = event.srcs
              }
              
              let index = event.index || 0
              wx.previewImage({
                  current: srcs[index],
                  urls: srcs
              })
              break
          case '5':

              break;
          case '6':
              o.checkCard()
              break;
          case '7':
              o.openLocation({
                  latitude: parseFloat(event.latitude),
                  longitude: parseFloat(event.longitude),
                  address: event.address,
                  scale: 14
              })
              break
          case '11':
              wx.pageScrollTo({ scrollTop: 0 })
              break
          case '13':
              t.onLoad()
              break
          case '20':
              o.scanCode()
              break
          case '23':
              break
          case '24':
              t.setData({ popupOpen: 0 })
              break
      }
  },
  scanCode() {
    wx.scanCode({
      success: (res) => {
        this.show = "结果:" + res.result + "二维码类型:" + res.scanType + "字符集:" + res.charSet + "路径:" + res.path;

        console.log(this.show)
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: (res) => {
        wx.showToast({
          title: '失败',
          icon: 'success',
          duration: 2000
        })
      },
      complete: (res) => {
      }
    })
  },
  globalData: {
      focus: false,
      shop_id: 1,
      hasLogin: false,
      cartList: [],
      _navbar: {
        navs: [{
          active: true,
          active_icon: '/images/home_active.png',
          icon: '/images/home.png',
          active_color: '#409eff',
          color: '#222',
          text: '首页',
          url: '/pages/index/index',
          new_url: '/pages/index/index'
        }, {
          active: false,
          active_icon: '/images/user_active.png',
          icon: '/images/user.png',
          active_color: '#409eff',
          color: '#222',
          text: '我的',
          url: '/pages/user/index',
          new_url: '/pages/user/index'
        }]
      },
      userInfo: false,
      shops: [],
      appid: "wxbb9a3d26845a4d74",
      secret: "8279c0d07bac6aa4c47d1010c9c8965f"
  },
};

for (var i in modules) args[modules[i].name] = require("" + modules[i].file);

App(args)